package com.ruoyi.web.controller.combat.apprisk;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.apprisk.AppUserRegisterBody;
import com.ruoyi.combat.domain.apprisk.CombatApplication;
import com.ruoyi.combat.service.apprisk.ICombatApplicationService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.combat.domain.apprisk.CombatPhone;
import com.ruoyi.combat.service.apprisk.ICombatPhoneService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 手机终端Controller
 *
 * @author ruoyi
 * @date 2024-08-21
 */
@Api(tags = "课题一：应用服务检测-手机终端管理接口")
@RestController
@RequestMapping("/combat/phone")
public class CombatPhoneController extends BaseController {
    @Autowired
    private ICombatPhoneService combatPhoneService;

    @Autowired
    private ICombatApplicationService combatApplicationService;

    /**
     * 查询手机终端列表
     */
    @PreAuthorize("@ss.hasPermi('system:phone:list')")
    @GetMapping("/list")
    @ApiOperation(value = "获取全部手机终端列表")
    public TableDataInfo list(CombatPhone combatPhone) {
        startPage();
        List<CombatPhone> list = combatPhoneService.selectCombatPhoneList(combatPhone);
        return getDataTable(list);
    }

    /**
     * 导出手机终端列表
     */
    @PreAuthorize("@ss.hasPermi('system:phone:export')")
    @Log(title = "导出手机终端列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出手机终端列表")
    public void export(HttpServletResponse response, CombatPhone combatPhone) {
        List<CombatPhone> list = combatPhoneService.selectCombatPhoneList(combatPhone);
        ExcelUtil<CombatPhone> util = new ExcelUtil<CombatPhone>(CombatPhone.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取手机终端详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:phone:query')")
    @GetMapping(value = "/{phoneId}")
    @ApiOperation(value = "根据终端id获取手机终端详细信息")
    public AjaxResult getInfo(@PathVariable("phoneId") Long phoneId) {
        return success(combatPhoneService.selectCombatPhoneByPhoneId(phoneId));
    }

    /**
     * 新增【手机终端】
     */
    @PreAuthorize("@ss.hasPermi('system:phone:add')")
    @Log(title = "【新增手机终端】", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增手机终端")
    public AjaxResult add(@RequestBody CombatPhone combatPhone) {
        return toAjax(combatPhoneService.insertCombatPhone(combatPhone));
    }

    /**
     * 修改【手机终端】
     */
    @PreAuthorize("@ss.hasPermi('system:phone:edit')")
    @Log(title = "【修改手机终端】", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改手机终端")
    public AjaxResult edit(@RequestBody CombatPhone combatPhone) {
        return toAjax(combatPhoneService.updateCombatPhone(combatPhone));
    }

    /**
     * 删除【手机终端】
     */
    @ApiOperation(value = "删除手机终端")
    @PreAuthorize("@ss.hasPermi('system:phone:remove')")
    @Log(title = "【删除手机终端】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{phoneIds}")
    public AjaxResult remove(@PathVariable Long[] phoneIds) {
        return toAjax(combatPhoneService.deleteCombatPhoneByPhoneIds(phoneIds));
    }

    /**
     * 根据终端手机id获取app列表
     */
    @PreAuthorize("@ss.hasPermi('system:phone:query')")
    @GetMapping(value = "/applist/{phoneId}")
    @ApiOperation(value = "根据终端手机id获取全部apk列表")
    public TableDataInfo getAPPInfo(@PathVariable("phoneId") Long phoneId) {
        startPage();
        List<CombatApplication> applications = combatApplicationService.selectCombatAppByPhoneId(phoneId);
        return getDataTable(applications);
    }

    @Anonymous
    @PostMapping("/register")
    @ApiOperation(value = "app用户注册")
    public AjaxResult register(@RequestBody AppUserRegisterBody user)
    {
        String msg = combatPhoneService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    @PostMapping("/registerEncodData")
    @Anonymous
    public AjaxResult registerEncodData(@RequestBody Map<String,String> data)
    {
        String key = "secret";
        String decrypt = decrypt(data.get("data"), key);
        AppUserRegisterBody user = JSONUtil.toBean(decrypt, AppUserRegisterBody.class);
        String msg = combatPhoneService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    public String decrypt(String encryptedText, String password) {
        StringBuilder result = new StringBuilder();

        // 每两个字符代表一个16进制字节
        for (int i = 0; i < encryptedText.length(); i += 2) {
            // 解析16进制字符串
            String hex = encryptedText.substring(i, i + 2);
            int charCode = Integer.parseInt(hex, 16);

            // 与密码字符异或（反向操作）
            int pwdChar = password.charAt((i/2) % password.length());
            charCode = charCode ^ pwdChar;

            // ASCII码反向位移（-5）
            charCode -= 5;

            result.append((char) charCode);
        }

        return result.toString();
    }

    /**
     * 根据终端手机id获取app列表
     */
    @PreAuthorize("@ss.hasPermi('system:phone:query')")
    @GetMapping(value = "/getPhoneAppRiskInfo/{phoneId}")
    @ApiOperation(value = "根据终端手机id获取全部apk列表")
    public AjaxResult getPhoneAppRiskInfo(@PathVariable("phoneId") Long phoneId) {
        List<Map> phoneAppRiskInfo = combatApplicationService.getPhoneAppRiskInfo(phoneId);
        return AjaxResult.success(phoneAppRiskInfo);
    }

    @GetMapping("/editStatus")
    @Anonymous
    public void editStatus(@RequestParam("phoneNum") String phoneNum, @RequestParam("status") String status){

        CombatPhone combatPhone = combatPhoneService.selectCombatPhoneByPhoneNum(phoneNum);
        if(combatPhone!=null){
            if("0".equals(status)){
                combatPhone.setPhoneState("离线");
            }else{
                combatPhone.setPhoneState("在线");
            }
        }
        combatPhoneService.updateCombatPhone(combatPhone);
    }
}
